package hmvictor.jpql;

import hmvictor.jpql.nodes.JpaJarChildrenFactory;
import hmvictor.jpql.nodes.JpaJarNode;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.view.ListView;
import org.openide.util.Exceptions;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.util.Utilities;
import org.openide.windows.WindowManager;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//hmvictor.jpql//JarExplorer//EN",
        autostore = false
)
@TopComponent.Description(
        preferredID = "JarExplorerTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE", 
        persistenceType = TopComponent.PERSISTENCE_ALWAYS
)
@TopComponent.Registration(mode = "explorer", openAtStartup = true)
@ActionID(category = "Window", id = "hmvictor.jpql.JarExplorerTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_JarExplorerAction",
        preferredID = "JarExplorerTopComponent"
)
@Messages({
    "CTL_JarExplorerAction=JarExplorer",
    "CTL_JarExplorerTopComponent=JPA Jars",
    "HINT_JarExplorerTopComponent=This is a JarExplorer window"
})
public final class JarExplorerTopComponent extends TopComponent implements ExplorerManager.Provider {

    private static final String JPA_JARS_FILE = "jpaJars.data";

    private final ExplorerManager explorerManager = new ExplorerManager();

    private final List<File> jarFiles = new LinkedList<>();

    public JarExplorerTopComponent() {
        initComponents();
        setName(Bundle.CTL_JarExplorerTopComponent());
        setToolTipText(Bundle.HINT_JarExplorerTopComponent());
        putClientProperty(TopComponent.PROP_CLOSING_DISABLED, Boolean.TRUE);
        listViewPanel.add(new ListView());
    }

    public List<URL> getJarUrls() throws MalformedURLException {
        List<URL> list = new LinkedList<>();
        for (File file : jarFiles) {
            list.add(Utilities.toURI(file).toURL());
        }
        return list;
    }

    public ClassLoader createClassLoader() throws MalformedURLException {
        List<URL> urls = getJarUrls();
        return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader());
    }

    public List<String> getUnitnames() throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
        List<String> unitnames = new LinkedList<>();
        ClassLoader classLoader = createClassLoader();
        Enumeration<URL> resources = classLoader.getResources("META-INF/persistence.xml");
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(resource.openStream());
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression expr = xpath.compile("persistence/persistence-unit/@name");
            NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < nl.getLength(); i++) {
                Node node = nl.item(i);
                unitnames.add(node.getNodeValue());
            }
        }
        return unitnames;
    }

    private void saveJarList() throws FileNotFoundException {
        File file = new File(AppFiles.getAndCreateConfigDir(), JPA_JARS_FILE);
        try (PrintWriter writer = new PrintWriter(file)) {
            jarFiles.forEach(f -> {
                writer.println(f.getAbsolutePath());
            });
        }
    }

    private void loadJarList() throws FileNotFoundException, IOException {
        File file = new File(AppFiles.getAndCreateConfigDir(), JPA_JARS_FILE);
        if (file.exists() && file.isFile()) {
            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    jarFiles.add(new File(line));
                }
            }
        }
        JPQLEditorTopComponent topComponent = (JPQLEditorTopComponent) WindowManager.getDefault().findTopComponent("JQPLEditorTopComponent");
        try {
            topComponent.setUnitNames(getUnitnames());
        } catch (ParserConfigurationException | SAXException | XPathExpressionException ex) {
            Exceptions.printStackTrace(ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fileChooser = new javax.swing.JFileChooser();
        listViewPanel = new javax.swing.JPanel();

        fileChooser.setFileFilter(new FileNameExtensionFilter("Jar file", "jar"));

        listViewPanel.setLayout(new java.awt.BorderLayout());

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(listViewPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(listViewPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFileChooser fileChooser;
    private javax.swing.JPanel listViewPanel;
    // End of variables declaration//GEN-END:variables
    
    @Override
    public void componentOpened() {
        try {
            loadJarList();
            jpaJarChildrenFactory = new JpaJarChildrenFactory(jarFiles);
            explorerManager.setRootContext(new JpaJarNode(jpaJarChildrenFactory));
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    
    private JpaJarChildrenFactory jpaJarChildrenFactory;

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    public ExplorerManager getExplorerManager() {
        return explorerManager;
    }

    public void removeJarFile(File file) {
        jarFiles.remove(file);
        jpaJarChildrenFactory.refreshChildren();
        try {
            saveJarList();
        } catch (FileNotFoundException ex) {
            Exceptions.printStackTrace(ex);
        }
    }

    public void addJpaJar(File selectedFile) {
        jarFiles.add(selectedFile);
        jpaJarChildrenFactory.refreshChildren();
        try {
            saveJarList();
        } catch (FileNotFoundException ex) {
            Exceptions.printStackTrace(ex);
        }
        JPQLEditorTopComponent topComponent = (JPQLEditorTopComponent) WindowManager.getDefault().findTopComponent("JQPLEditorTopComponent");
        try {
            topComponent.setUnitNames(getUnitnames());
        } catch (IOException | ParserConfigurationException | SAXException | XPathExpressionException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    
}
